package com.jacky.iot;

import com.jacky.iot.resources.HelloWorldResource;
import com.jacky.iot.resources.PubSubResource;
import org.eclipse.californium.core.CoapServer;
import org.eclipse.californium.core.config.CoapConfig;
import org.eclipse.californium.core.network.CoapEndpoint;
import org.eclipse.californium.core.server.resources.MyIpResource;
import org.eclipse.californium.elements.config.Configuration;
import org.eclipse.californium.elements.config.TcpConfig;
import org.eclipse.californium.elements.config.UdpConfig;
import org.eclipse.californium.elements.tcp.netty.TcpServerConnector;
import org.eclipse.californium.elements.util.NetworkInterfacesUtil;

import java.net.InetAddress;
import java.net.InetSocketAddress;

public class HelloWorldServer extends CoapServer {

    static {
        CoapConfig.register();
        UdpConfig.register();
        TcpConfig.register();
    }

    public HelloWorldServer() {
        add(new HelloWorldResource());
        add(new PubSubResource());
        add(new MyIpResource(MyIpResource.RESOURCE_NAME, true));
    }

    public static void main(String[] args) {
        boolean udp = true;
        boolean tcp = false;

        Integer port = Configuration.getStandard().get(CoapConfig.COAP_PORT);
        if (args.length > 0) {
            tcp = args[0].equals("coap+tcp:");
            if (tcp) {
                System.out.println("支持tcp");
            }
        }
        HelloWorldServer server = new HelloWorldServer();
        server.addEndpoints(udp, tcp, port);
        server.start();
    }

    private void addEndpoints(boolean udp, boolean tcp, int port) {
        Configuration config = Configuration.getStandard();
        for (InetAddress address : NetworkInterfacesUtil.getNetworkInterfaces()) {
            InetSocketAddress bindAddr = new InetSocketAddress(address, port);
            if (udp) {
                CoapEndpoint.Builder builder = new CoapEndpoint.Builder();
                builder.setInetSocketAddress(bindAddr);
                builder.setConfiguration(config);
                addEndpoint(builder.build());
                System.out.println("coap udp start up at:" + bindAddr.getHostString() + ":" + port);
            }
            if (tcp) {
                TcpServerConnector connector = new TcpServerConnector(bindAddr, config);
                CoapEndpoint.Builder builder = new CoapEndpoint.Builder();
                builder.setConnector(connector);
                builder.setConfiguration(config);
                addEndpoint(builder.build());
                System.out.println("coap udp start up at:" + bindAddr.getHostString() + ":" + port);
            }
        }
    }
}
